package com.example.lambda.stream;

import com.example.lambda.stream.entity.Boy;
import com.example.lambda.stream.entity.Girl;
import org.junit.Test;

import java.util.Optional;

/**
 * @author readpage
 * @create 2022-10-24 9:28
 */
public class OptionalTest {

    /**
     * Optional.of(T t):    创建一个Optional实例,t必须非空
     * Optional.empty():    创建一个空的Optional实例
     * Optional.ofNullable(T t):    t可以为null
     */
    @Test
    public void test() {
        Girl girl = new Girl();
//        girl = null;
        //of(T t): 保证t是非空的
        Optional<Girl> optionalGirl = Optional.of(girl);
    }

    @Test
    public void test2() {
        Girl girl = new Girl();
        girl = null;
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGirl);
        //orElse(T t): 如果当前的Optional内部封装的t是非空的，则返回内部的t.
        //如果内部的t是空的，则返回orElse()方法中的参数t1.
        Girl girl2 = optionalGirl.orElse(new Girl("jack"));
        System.out.println(girl2);
    }

    private String getGirlName(Boy boy) {
        if (boy != null) {
            Girl girl = boy.getGirl();
            if (girl != null) {
                return girl.getName();
            }
        }
        return null;
    }

    //使用Optional类的getGirlName():
    public String getGirlName2(Boy boy) {
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        Boy boyValue = boyOptional.orElse(new Boy(new Girl("tom")));
        Optional<Girl> girlOptional = Optional.ofNullable(boyValue.getGirl());
        Girl jack = girlOptional.orElse(new Girl("jack"));
        return jack.getName();
    }

    @Test
    public void test3() {
        Boy boy = new Boy();
//        boy = null;
        String girlName = getGirlName(boy);
        System.out.println(girlName);
        System.out.println(getGirlName2(boy));
        boy = null;
        System.out.println(getGirlName2(boy));
    }
}
